import React, { useEffect, useState } from 'react';
import { Box, CircularProgress, Alert, Snackbar } from '@mui/material';

import { useAuth, useAppNotifications, initializeStores } from './stores';
import { AppLayout } from './components/layout/AppLayout';
import { AppRouter } from './routes/AppRouter';
import { commonStyles } from './styles/utils';

// 应用初始化状态
type InitStatus = 'loading' | 'success' | 'error';

const App: React.FC = () => {
  const [initStatus, setInitStatus] = useState<InitStatus>('loading');
  const [initError, setInitError] = useState<string | null>(null);
  
  const { isAuthenticated } = useAuth();
  const { toasts, removeToast } = useAppNotifications();

  // 应用初始化
  useEffect(() => {
    const initializeApp = async () => {
      try {
        setInitStatus('loading');
        
        // 简化初始化过程，只做基本设置
        // 设置超时，防止初始化过程卡住
        const initPromise = initializeStores();
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('初始化超时')), 5000);
        });
        
        await Promise.race([initPromise, timeoutPromise]).catch(err => {
          console.warn('初始化警告:', err);
          // 即使超时也继续执行
        });
        
        // 无论如何都设置为成功，让应用继续渲染
        setInitStatus('success');
      } catch (error) {
        console.error('应用初始化失败:', error);
        setInitError(error instanceof Error ? error.message : '未知错误');
        // 即使出错也尝试继续渲染应用
        setInitStatus('success');
      }
    };

    initializeApp();
  }, []);

  // 应用加载中
  if (initStatus === 'loading') {
    return (
      <Box sx={commonStyles.flexColumnCenter} minHeight="100vh">
        <CircularProgress size={60} thickness={4} />
        <Box sx={{ mt: 2, fontSize: '1.1rem', color: 'text.secondary' }}>
          正在初始化应用...
        </Box>
      </Box>
    );
  }

  // 应用初始化失败
  if (initStatus === 'error') {
    return (
      <Box sx={commonStyles.flexColumnCenter} minHeight="100vh" p={3}>
        <Alert 
          severity="error" 
          sx={{ maxWidth: 400, mb: 2 }}
          action={
            <button 
              onClick={() => window.location.reload()}
              style={{ 
                background: 'none', 
                border: 'none', 
                color: 'inherit',
                cursor: 'pointer',
                textDecoration: 'underline'
              }}
            >
              重试
            </button>
          }
        >
          应用初始化失败：{initError}
        </Alert>
      </Box>
    );
  }

  return (
    <>
      {/* 主要应用内容 */}
      {isAuthenticated ? (
        <AppLayout>
          <AppRouter />
        </AppLayout>
      ) : (
        <AppRouter />
      )}

      
      {/* 全局Toast通知 */}
      {toasts.map((toast) => (
        <Snackbar
          key={toast.id}
          open={true}
          autoHideDuration={toast.duration}
          onClose={() => removeToast(toast.id)}
          anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
          sx={{ mt: 1 }}
        >
          <Alert
            severity={toast.type}
            variant="filled"
            onClose={() => removeToast(toast.id)}
            action={
              toast.action && (
                <button
                  onClick={toast.action.onClick}
                  style={{
                    background: 'none',
                    border: 'none',
                    color: 'inherit',
                    cursor: 'pointer',
                    textDecoration: 'underline',
                    marginLeft: 8,
                  }}
                >
                  {toast.action.label}
                </button>
              )
            }
          >
            <Box>
              <Box sx={{ fontWeight: 'bold' }}>{toast.title}</Box>
              {toast.message && (
                <Box sx={{ fontSize: '0.875rem', mt: 0.5 }}>
                  {toast.message}
                </Box>
              )}
            </Box>
          </Alert>
        </Snackbar>
      ))}
    </>
  );
};

export default App;